import json
from flask import Blueprint, render_template, request, jsonify
from apps.common.utils.rights import authorize
from apps.modules.admin.models.sys.sys_options import Options
from apps.extensions import db

options_bp = Blueprint('options', __name__, url_prefix='/options')

'''
系统配置
'''
@options_bp.get('/menu/')
@authorize("admin:sys:options:menu", log=True)
def menu():
    return render_template('system/options/menu.html')

@options_bp.post('/menu/save')
@authorize("admin:sys:options:menu", log=True)
def save_menu():
    """保存菜单数据"""
    try:
        data = request.get_json()
        menu_name = data.get('name', 'primary')
        menu_items = data.get('items', [])
        
        # 将菜单数据转换为JSON字符串
        menu_json = json.dumps(menu_items, ensure_ascii=False, indent=2)
        
        # 查找是否已存在该菜单的配置
        existing_option = Options.query.filter_by(
            option_type='menu',
            option_name=menu_name
        ).first()
        
        if existing_option:
            # 更新现有配置
            existing_option.option_value = menu_json
            db.session.commit()
            message = f"菜单 '{menu_name}' 已更新"
        else:
            # 创建新配置
            new_option = Options(
                option_type='menu',
                option_name=menu_name,
                option_value=menu_json,
                autoload='yes'
            )
            db.session.add(new_option)
            db.session.commit()
            message = f"菜单 '{menu_name}' 已保存"
        
        return jsonify({
            'success': True,
            'message': message,
            'data': {
                'name': menu_name,
                'items_count': len(menu_items)
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'保存失败: {str(e)}'
        }), 500

@options_bp.get('/menu/load/<menu_name>')
@authorize("admin:sys:options:menu", log=True)
def load_menu(menu_name):
    """加载菜单数据"""
    try:
        # 查找菜单配置
        option = Options.query.filter_by(
            option_type='menu',
            option_name=menu_name
        ).first()
        
        if option:
            menu_items = json.loads(option.option_value)
            return jsonify({
                'success': True,
                'data': {
                    'name': menu_name,
                    'items': menu_items
                }
            })
        else:
            return jsonify({
                'success': False,
                'message': f'菜单 "{menu_name}" 不存在'
            }), 404
            
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'加载失败: {str(e)}'
        }), 500

@options_bp.get('/menu/list')
@authorize("admin:sys:options:menu", log=True)
def list_menus():
    """获取所有菜单列表"""
    try:
        # 查找所有菜单配置
        options = Options.query.filter_by(option_type='menu').all()
        
        menus = []
        for option in options:
            try:
                menu_items = json.loads(option.option_value)
                menus.append({
                    'name': option.option_name,
                    'items_count': len(menu_items),
                    'created_at': option.id  # 使用ID作为创建时间标识
                })
            except:
                # 如果JSON解析失败，跳过该菜单
                continue
        
        return jsonify({
            'success': True,
            'data': menus
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取菜单列表失败: {str(e)}'
        }), 500

@options_bp.delete('/menu/delete/<menu_name>')
@authorize("admin:sys:options:menu", log=True)
def delete_menu(menu_name):
    """删除菜单"""
    try:
        # 查找菜单配置
        option = Options.query.filter_by(
            option_type='menu',
            option_name=menu_name
        ).first()
        
        if option:
            db.session.delete(option)
            db.session.commit()
            return jsonify({
                'success': True,
                'message': f'菜单 "{menu_name}" 已删除'
            })
        else:
            return jsonify({
                'success': False,
                'message': f'菜单 "{menu_name}" 不存在'
            }), 404
            
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'删除失败: {str(e)}'
        }), 500

@options_bp.get('/custom/')
@authorize("admin:sys:options:custom", log=True)
def custom():
    return render_template('system/options/custom.html')

@options_bp.post('/custom/save')
@authorize("admin:sys:options:custom", log=True)
def save_custom():
    """保存常规设置"""
    try:
        data = request.get_json()
        
        # 定义需要保存的字段
        fields = [
            'site_title',           # 站点标题
            'site_tagline',         # 副标题
            'site_icon',            # 站点图标
            'wordpress_url',        # WordPress 地址 (URL)
            'site_url',             # 站点地址 (URL)
            'admin_email',          # 管理员邮箱地址
            'users_can_register',   # 成员资格
            'default_role',         # 新用户默认角色
            'site_language',        # 站点语言
            'timezone'              # 时区
        ]
        
        saved_count = 0
        
        for field in fields:
            value = data.get(field, '')
            
            # 查找是否已存在该配置
            existing_option = Options.query.filter_by(
                option_type='custom',
                option_name=field
            ).first()
            
            if existing_option:
                # 更新现有配置
                existing_option.option_value = str(value)
                saved_count += 1
            else:
                # 创建新配置
                new_option = Options(
                    option_type='custom',
                    option_name=field,
                    option_value=str(value),
                    autoload='yes'
                )
                db.session.add(new_option)
                saved_count += 1
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': f'成功保存 {saved_count} 项设置',
            'data': {
                'saved_count': saved_count
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'保存失败: {str(e)}'
        }), 500

@options_bp.get('/custom/load')
@authorize("admin:sys:options:custom", log=True)
def load_custom():
    """加载常规设置"""
    try:
        # 查找所有custom类型的配置
        options = Options.query.filter_by(option_type='custom').all()
        
        settings = {}
        for option in options:
            settings[option.option_name] = option.option_value
        
        return jsonify({
            'success': True,
            'data': settings
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'加载失败: {str(e)}'
        }), 500